package com.jdone.compus.controller;

import com.jdone.compus.utils.HttpUtil;
import com.jdone.compus.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@RestController
@RequestMapping("/wechat")
public class WeChatController {

    @Value("${wechat.appid}")
    private String appId;
    
    @Value("${wechat.appsecret}")
    private String appSecret;
    
    // 用于缓存access_token和jsapi_ticket
    private static String accessToken;
    private static long accessTokenExpireTime;
    private static String jsapiTicket;
    private static long jsapiTicketExpireTime;

    /**
     * 获取JS-SDK配置信息
     */
    @GetMapping("/js-sdk-config")
    public Map<String, String> getJsSdkConfig(@RequestParam String url) {
        try {
            // 获取jsapi_ticket
            String ticket = getJsapiTicket();
            
            // 生成随机字符串
            String noncestr = UUID.randomUUID().toString().replaceAll("-", "");
            
            // 生成时间戳
            long timestamp = System.currentTimeMillis() / 1000;
            
            // 拼接签名字符串
            String signatureStr = "jsapi_ticket=" + ticket +
                                 "&noncestr=" + noncestr +
                                 "&timestamp=" + timestamp +
                                 "&url=" + url;
            
            // 生成签名
            String signature = sha1(signatureStr);
            
            // 组装返回结果
            Map<String, String> result = new HashMap<>();
            result.put("appId", appId);
            result.put("timestamp", String.valueOf(timestamp));
            result.put("nonceStr", noncestr);
            result.put("signature", signature);
            
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取JS-SDK配置失败");
        }
    }
    
    /**
     * 获取jsapi_ticket
     */
    private String getJsapiTicket() throws Exception {
        // 判断ticket是否过期
        if (jsapiTicket == null || System.currentTimeMillis() >= jsapiTicketExpireTime) {
            // 获取access_token
            String token = getAccessToken();
            
            // 调用微信接口获取jsapi_ticket
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
            String result = HttpUtil.sendGet(url);
            
            // 解析返回结果 (这里需要根据实际返回格式解析，建议使用Jackson或Gson)
            // 示例JSON: {"errcode":0,"errmsg":"ok","ticket":"xxx","expires_in":7200}
            Map<String, Object> response = JsonUtil.parseJsonToMap(result);
            
            if (response.get("errcode").toString().equals("0")) {
                jsapiTicket = response.get("ticket").toString();
                // 过期时间设置为7100秒，比实际过期时间少100秒，避免临界点问题
                jsapiTicketExpireTime = System.currentTimeMillis() + 7100 * 1000;
            } else {
                throw new RuntimeException("获取jsapi_ticket失败: " + response.get("errmsg"));
            }
        }
        return jsapiTicket;
    }
    
    /**
     * 获取access_token
     */
    private String getAccessToken() throws Exception {
        // 判断access_token是否过期
        if (accessToken == null || System.currentTimeMillis() >= accessTokenExpireTime) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                       "&appid=" + appId +
                       "&secret=" + appSecret;
            
            String result = HttpUtil.sendGet(url);
            
            // 解析返回结果
            Map<String, Object> response = JsonUtil.parseJsonToMap(result);
            
            if (response.containsKey("access_token")) {
                accessToken = response.get("access_token").toString();
                // 过期时间设置为7100秒，比实际过期时间少100秒
                accessTokenExpireTime = System.currentTimeMillis() + 7100 * 1000;
            } else {
                throw new RuntimeException("获取access_token失败: " + response.get("errmsg"));
            }
        }
        return accessToken;
    }
    
    /**
     * SHA1加密
     */
    private String sha1(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte[] messageDigest = digest.digest();
            
            // 转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}
